﻿using EYWeb.Core;
using EYWeb.Core.Cache;
using EYWeb.Domain.Entities;
using EYWeb.Services;
using EYWeb.WebLTE.App_Start.Handler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace EYWeb.WebLTE.Controllers
{
    [Login]
    public class MenuController : Controller
    {
        private readonly IModuleService _moduleService;

        public MenuController(IModuleService moduleService)
        {
            this._moduleService = moduleService;
        }

        [AjaxOnly]
        public ActionResult GetMenu()
        {
            string roleId = OperatorProvider.Provider.GetCurrent().RoleId;
            string data = CacheFactory.Cache.GetCache<string>("eyweb_menu_"+ roleId);
            if(string.IsNullOrEmpty(data))
            {
                data = ToMenuJson(_moduleService.GetMenuList(roleId), "0");
                CacheFactory.Cache.WriteCache<string>("eyweb_menu_" + roleId, data);
            }

            return Content(data);
        }

        private string ToMenuJson(List<ModuleEntity> data, string parentId)
        {
            StringBuilder sbJson = new StringBuilder();
            sbJson.Append("[");
            List<ModuleEntity> entitys = data.FindAll(t => t.ParentId == parentId);
            if (entitys.Count > 0)
            {
                foreach (var item in entitys)
                {
                    string strJson = item.ToJson();
                    strJson = strJson.Insert(strJson.Length - 1, ",\"ChildNodes\":" + ToMenuJson(data, item.Id) + "");
                    sbJson.Append(strJson + ",");
                }
                sbJson = sbJson.Remove(sbJson.Length - 1, 1);
            }
            sbJson.Append("]");
            return sbJson.ToString();
        }

    }



}